<template>
  <div class="admin-templates-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>项目后台模板</h1>
          <p>精选优质后台管理系统模板，快速启动您的项目开发</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ templates.length }}</span>
            <span class="stat-label">模板数量</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ totalDownloads }}</span>
            <span class="stat-label">总下载数</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filters-section">
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索模板名称、技术栈..."
          prefix-icon="Search"
          size="large"
          clearable
        />
      </div>
      <div class="filter-tabs">
        <el-radio-group v-model="activeCategory" size="large">
          <el-radio-button label="all">
            全部
          </el-radio-button>
          <el-radio-button label="vue">
            Vue
          </el-radio-button>
          <el-radio-button label="react">
            React
          </el-radio-button>
          <el-radio-button label="angular">
            Angular
          </el-radio-button>
          <el-radio-button label="admin">
            传统
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 模板卡片网格 -->
    <div class="templates-grid">
      <div
        v-for="template in filteredTemplates"
        :key="template.id"
        class="template-card"
        @click="viewTemplate(template)"
      >
        <!-- 模板封面 -->
        <div class="template-cover">
          <img :src="template.cover" :alt="template.name" loading="lazy">
          <div class="cover-overlay">
            <div class="overlay-actions">
              <el-button type="primary" size="large" @click.stop="downloadTemplate(template)">
                <el-icon><Download /></el-icon>
                立即下载
              </el-button>
              <el-button size="large" @click.stop="previewTemplate(template)">
                <el-icon><View /></el-icon>
                在线预览
              </el-button>
            </div>
          </div>

          <!-- 技术栈标签 -->
          <div class="tech-stack">
            <el-tag
              v-for="tech in template.techStack"
              :key="tech"
              size="small"
              :type="getTechTagType(tech)"
            >
              {{ tech }}
            </el-tag>
          </div>
        </div>

        <!-- 模板信息 -->
        <div class="template-info">
          <h3 class="template-title">
            {{ template.name }}
          </h3>
          <p class="template-description">
            {{ template.description }}
          </p>

          <div class="template-meta">
            <div class="meta-left">
              <span class="author">
                <el-icon><User /></el-icon>
                {{ template.author }}
              </span>
              <span class="version">
                <el-icon><PriceTag /></el-icon>
                v{{ template.version }}
              </span>
            </div>
            <div class="meta-right">
              <span class="downloads">
                <el-icon><Download /></el-icon>
                {{ formatNumber(template.downloads) }}
              </span>
              <span class="stars">
                <el-icon><Star /></el-icon>
                {{ template.stars }}
              </span>
            </div>
          </div>

          <div class="template-features">
            <el-tag
              v-for="feature in template.features.slice(0, 3)"
              :key="feature"
              size="small"
              effect="plain"
            >
              {{ feature }}
            </el-tag>
            <span v-if="template.features.length > 3" class="more-features">
              +{{ template.features.length - 3 }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button size="large" @click="loadMore" :loading="loading">
        加载更多模板
      </el-button>
    </div>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedTemplate?.name"
      width="900px"
      class="template-detail-dialog"
    >
      <div v-if="selectedTemplate" class="template-detail">
        <div class="detail-header">
          <img :src="selectedTemplate.cover" :alt="selectedTemplate.name" class="detail-cover">
          <div class="detail-info">
            <h2>{{ selectedTemplate.name }}</h2>
            <p class="detail-description">
              {{ selectedTemplate.fullDescription }}
            </p>

            <div class="detail-meta">
              <div class="meta-item">
                <span class="label">作者：</span>
                <span class="value">{{ selectedTemplate.author }}</span>
              </div>
              <div class="meta-item">
                <span class="label">版本：</span>
                <span class="value">v{{ selectedTemplate.version }}</span>
              </div>
              <div class="meta-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ selectedTemplate.updateTime }}</span>
              </div>
              <div class="meta-item">
                <span class="label">下载次数：</span>
                <span class="value">{{ formatNumber(selectedTemplate.downloads) }}</span>
              </div>
            </div>

            <div class="detail-actions">
              <el-button type="primary" size="large" @click="downloadTemplate(selectedTemplate)">
                <el-icon><Download /></el-icon>
                下载模板
              </el-button>
              <el-button size="large" @click="previewTemplate(selectedTemplate)">
                <el-icon><View /></el-icon>
                在线预览
              </el-button>
              <el-button size="large" @click="openGiteeRepo(selectedTemplate)">
                <el-icon><Link /></el-icon>
                Gitee仓库
              </el-button>
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="content-section">
            <h3>技术栈</h3>
            <div class="tech-stack-detail">
              <el-tag
                v-for="tech in selectedTemplate.techStack"
                :key="tech"
                size="large"
                :type="getTechTagType(tech)"
              >
                {{ tech }}
              </el-tag>
            </div>
          </div>

          <div class="content-section">
            <h3>功能特性</h3>
            <ul class="features-list">
              <li v-for="feature in selectedTemplate.features" :key="feature">
                <el-icon><Check /></el-icon>
                {{ feature }}
              </li>
            </ul>
          </div>

          <div class="content-section">
            <h3>项目截图</h3>
            <div class="screenshots">
              <img
                v-for="(screenshot, index) in selectedTemplate.screenshots"
                :key="index"
                :src="screenshot"
                :alt="`截图 ${index + 1}`"
                @click="previewImage(screenshot)"
              >
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Check, Download, Link, PriceTag, Star, User, View } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, onMounted, ref } from "vue"

interface AdminTemplate {
  id: string
  name: string
  description: string
  fullDescription: string
  cover: string
  screenshots: string[]
  author: string
  version: string
  updateTime: string
  downloads: number
  stars: number
  techStack: string[]
  features: string[]
  category: string
  giteeUrl: string
  previewUrl: string
}

// 响应式数据
const searchText = ref("")
const activeCategory = ref("all")
const loading = ref(false)
const hasMore = ref(true)
const detailDialogVisible = ref(false)
const selectedTemplate = ref<AdminTemplate | null>(null)

// 模板数据
const templates = ref<AdminTemplate[]>([
  {
    id: "v3-admin-vite",
    name: "V3 Admin Vite",
    description: "基于Vue3 + Element Plus + Vite的现代化后台管理系统",
    fullDescription: "一套基于Vue3、TypeScript、Element Plus、Vite、Pinia的现代化后台管理系统。采用最新的前端技术栈，具有完整的权限管理、动态路由、多主题等功能。代码规范、架构清晰，适合企业级项目开发。",
    cover: "/banner01.png",
    screenshots: [
      "/banner01.png",
      "/banner02.png",
      "/banner03.png"
    ],
    author: "cheng-long-x",
    version: "4.3.0",
    updateTime: "2025-03-20",
    downloads: 35600,
    stars: 1280,
    techStack: ["Vue3", "TypeScript", "Element Plus", "Vite", "Pinia", "UnoCSS"],
    features: ["用户权限管理", "动态路由", "多主题切换", "国际化", "响应式布局", "TypeScript支持", "ESLint规范", "Prettier格式化"],
    category: "vue",
    giteeUrl: "https://gitee.com/cheng-long-x/v3-admin-vite-main",
    previewUrl: "https://v3-admin-vite.demo.com"
  },
  {
    id: "ant-design-pro",
    name: "Ant Design Pro",
    description: "开箱即用的中台前端/设计解决方案",
    fullDescription: "Ant Design Pro 是基于 Ant Design 和 umi 的封装的一整套企业级中后台前端/设计解决方案，致力于在设计规范和基础组件的基础上，继续向上构建，提炼出典型模板/业务组件/配套设计资源。",
    cover: "https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg",
    screenshots: [
      "https://gw.alipayobjects.com/zos/antfincdn/mKUOqIGKvH/pro1.png",
      "https://gw.alipayobjects.com/zos/antfincdn/HiGfgAkJ3K/pro2.png",
      "https://gw.alipayobjects.com/zos/antfincdn/HlrTcOCyFJ/pro3.png"
    ],
    author: "Ant Design",
    version: "6.0.0",
    updateTime: "2025-03-18",
    downloads: 58200,
    stars: 2150,
    techStack: ["React", "TypeScript", "Ant Design", "Umi", "ProComponents"],
    features: ["权限管理", "国际化", "主题定制", "ProTable", "ProForm", "微前端", "数据流"],
    category: "react",
    giteeUrl: "https://gitee.com/ant-design/ant-design-pro",
    previewUrl: "https://preview.pro.ant.design"
  },
  {
    id: "angular-material-admin",
    name: "Angular Material Admin",
    description: "基于Angular + Material Design的管理后台",
    fullDescription: "采用Angular最新版本和Material Design设计语言的后台管理系统。具有优雅的界面设计和丰富的组件库。",
    cover: "https://picsum.photos/400/250?random=3",
    screenshots: [
      "https://picsum.photos/800/500?random=31",
      "https://picsum.photos/800/500?random=32"
    ],
    author: "Angular Team",
    version: "3.2.1",
    updateTime: "2025-03-10",
    downloads: 12500,
    stars: 423,
    techStack: ["Angular", "TypeScript", "Material Design", "RxJS", "NgRx"],
    features: ["Material Design", "响应式设计", "服务端渲染", "懒加载", "PWA支持"],
    category: "angular",
    giteeUrl: "https://gitee.com/example/angular-material-admin",
    previewUrl: "https://angular-material-admin.demo.com"
  },
  {
    id: "layui-admin",
    name: "LayUI Admin",
    description: "经典LayUI后台管理系统，简洁易用",
    fullDescription: "基于LayUI框架开发的经典后台管理系统。界面简洁、功能完善，适合快速开发中小型管理系统。",
    cover: "https://picsum.photos/400/250?random=4",
    screenshots: [
      "https://picsum.photos/800/500?random=41",
      "https://picsum.photos/800/500?random=42"
    ],
    author: "LayUI",
    version: "2.5.6",
    updateTime: "2025-03-08",
    downloads: 35600,
    stars: 756,
    techStack: ["LayUI", "jQuery", "HTML5", "CSS3"],
    features: ["经典界面", "易于上手", "兼容性好", "文档完善", "社区活跃"],
    category: "admin",
    giteeUrl: "https://gitee.com/example/layui-admin",
    previewUrl: "https://layui-admin.demo.com"
  },
  {
    id: "bootstrap-admin",
    name: "Bootstrap Admin",
    description: "基于Bootstrap的响应式后台管理模板",
    fullDescription: "采用Bootstrap框架构建的响应式后台管理模板。兼容性强，适配各种设备和浏览器。",
    cover: "https://picsum.photos/400/250?random=5",
    screenshots: [
      "https://picsum.photos/800/500?random=51",
      "https://picsum.photos/800/500?random=52"
    ],
    author: "Bootstrap",
    version: "4.1.2",
    updateTime: "2025-03-05",
    downloads: 28900,
    stars: 567,
    techStack: ["Bootstrap", "jQuery", "JavaScript", "SCSS"],
    features: ["响应式设计", "兼容性强", "组件丰富", "自定义主题", "文档齐全"],
    category: "admin",
    giteeUrl: "https://gitee.com/example/bootstrap-admin",
    previewUrl: "https://bootstrap-admin.demo.com"
  },
  {
    id: "vue2-element-admin",
    name: "Vue2 Element Admin",
    description: "经典Vue2 + Element UI后台管理系统",
    fullDescription: "基于Vue2和Element UI的经典后台管理系统。功能完善，生态成熟，适合企业级项目开发。",
    cover: "https://picsum.photos/400/250?random=6",
    screenshots: [
      "https://picsum.photos/800/500?random=61",
      "https://picsum.photos/800/500?random=62"
    ],
    author: "PanJiaChen",
    version: "4.4.0",
    updateTime: "2025-03-01",
    downloads: 45200,
    stars: 1234,
    techStack: ["Vue2", "Element UI", "Vuex", "Vue Router", "Axios"],
    features: ["权限验证", "错误日志", "富文本编辑器", "Excel导入导出", "图表组件"],
    category: "vue",
    giteeUrl: "https://gitee.com/example/vue2-element-admin",
    previewUrl: "https://vue2-element-admin.demo.com"
  }
])

// 计算属性
const filteredTemplates = computed(() => {
  let filtered = templates.value

  // 按分类筛选
  if (activeCategory.value !== "all") {
    filtered = filtered.filter(template => template.category === activeCategory.value)
  }

  // 按搜索文本筛选
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(searchLower)
      || template.description.toLowerCase().includes(searchLower)
      || template.techStack.some(tech => tech.toLowerCase().includes(searchLower))
    )
  }

  return filtered
})

const totalDownloads = computed(() => {
  return templates.value.reduce((total, template) => total + template.downloads, 0)
})

// 方法
function getTechTagType(tech: string) {
  const typeMap: Record<string, string> = {
    "Vue3": "success",
    "Vue2": "success",
    "React": "primary",
    "Angular": "danger",
    "TypeScript": "warning",
    "JavaScript": "info",
    "Element Plus": "success",
    "Element UI": "success",
    "Ant Design": "primary",
    "LayUI": "",
    "Bootstrap": "info"
  }
  return typeMap[tech] || ""
}

function formatNumber(num: number) {
  if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`
  }
  return num.toString()
}

function viewTemplate(template: AdminTemplate) {
  selectedTemplate.value = template
  detailDialogVisible.value = true
}

async function downloadTemplate(template: AdminTemplate) {
  try {
    ElMessage.success(`正在准备下载 ${template.name}...`)

    // 这里后期替换为真实的下载逻辑
    // 可以是直接跳转到Gitee发布页面或者调用下载API
    window.open(`${template.giteeUrl}/releases`, "_blank")

    // 更新下载次数
    template.downloads++
  } catch (error) {
    ElMessage.error("下载失败，请稍后重试")
    console.error("下载失败:", error)
  }
}

function previewTemplate(template: AdminTemplate) {
  if (template.previewUrl) {
    window.open(template.previewUrl, "_blank")
  } else {
    ElMessage.info("该模板暂无在线预览")
  }
}

function openGiteeRepo(template: AdminTemplate) {
  window.open(template.giteeUrl, "_blank")
}

function previewImage(imageUrl: string) {
  // 可以使用Element Plus的图片预览组件
  window.open(imageUrl, "_blank")
}

function loadMore() {
  loading.value = true
  // 模拟加载更多数据
  setTimeout(() => {
    loading.value = false
    hasMore.value = false
    ElMessage.info("已加载全部模板")
  }, 1000)
}

onMounted(() => {
  // 页面加载完成后的初始化操作
})
</script>

<style scoped lang="scss">
.admin-templates-page {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 16px;

  // 确保容器能够完全包含内容
  display: flex;
  flex-direction: column;

  // 使用全屏宽度，不限制最大宽度
  width: 100%;
  box-sizing: border-box;

  .page-header {
    margin-bottom: 24px;
    background: white;
    border-radius: 12px;
    padding: 24px 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-text {
        h1 {
          font-size: 36px;
          font-weight: 700;
          color: #2c3e50;
          margin: 0 0 8px 0;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }

        p {
          font-size: 16px;
          color: #7f8c8d;
          margin: 0;
        }
      }

      .header-stats {
        display: flex;
        gap: 32px;

        .stat-item {
          text-align: center;

          .stat-number {
            display: block;
            font-size: 28px;
            font-weight: 700;
            color: #3498db;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: #95a5a6;
          }
        }
      }
    }
  }

  .filters-section {
    margin-bottom: 20px;
    display: flex;
    gap: 24px;
    align-items: center;
    justify-content: space-between;
    background: white;
    border-radius: 12px;
    padding: 16px 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    .search-box {
      flex: 1;
      max-width: 420px;

      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: 8px;
          border: 1px solid #e1e5e9;
          box-shadow: none;
          transition: all 0.2s ease;

          &:hover {
            border-color: #c0c4cc;
          }

          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }
      }
    }

    .filter-tabs {
      .el-radio-group {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 3px;
        border: 1px solid #e9ecef;

        .el-radio-button {
          .el-radio-button__inner {
            border: none;
            background: transparent;
            color: #6c757d;
            font-weight: 500;
            padding: 8px 16px;
            border-radius: 6px;
            transition: all 0.2s ease;

            &:hover {
              background: rgba(64, 158, 255, 0.08);
              color: #409eff;
            }
          }

          &.is-active .el-radio-button__inner {
            background: #409eff;
            color: white;
            box-shadow: 0 1px 3px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }
  }

  .templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    .template-card {
      background: white;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);

        .cover-overlay {
          opacity: 1;
        }
      }

      .template-cover {
        position: relative;
        height: 220px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        &:hover img {
          transform: scale(1.05);
        }

        .cover-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          .overlay-actions {
            display: flex;
            gap: 12px;
          }
        }

        .tech-stack {
          position: absolute;
          top: 12px;
          left: 12px;
          display: flex;
          flex-wrap: wrap;
          gap: 6px;

          .el-tag {
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.9);
          }
        }
      }

      .template-info {
        padding: 20px;

        .template-title {
          font-size: 20px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 8px 0;
        }

        .template-description {
          font-size: 14px;
          color: #7f8c8d;
          line-height: 1.5;
          margin: 0 0 16px 0;
        }

        .template-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          font-size: 12px;
          color: #95a5a6;

          .meta-left,
          .meta-right {
            display: flex;
            gap: 12px;
            align-items: center;
          }

          .author,
          .version,
          .downloads,
          .stars {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }

        .template-features {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          align-items: center;

          .more-features {
            font-size: 12px;
            color: #95a5a6;
          }
        }
      }
    }
  }

  .load-more {
    text-align: center;
    margin-top: 32px;
  }
}

// 对话框样式
:deep(.template-detail-dialog) {
  .el-dialog__body {
    padding: 0;
  }

  .template-detail {
    .detail-header {
      display: flex;
      gap: 24px;
      padding: 24px;
      border-bottom: 1px solid #ebeef5;

      .detail-cover {
        width: 300px;
        height: 200px;
        object-fit: cover;
        border-radius: 8px;
        flex-shrink: 0;
      }

      .detail-info {
        flex: 1;

        h2 {
          margin: 0 0 12px 0;
          color: #2c3e50;
        }

        .detail-description {
          color: #7f8c8d;
          line-height: 1.6;
          margin-bottom: 20px;
        }

        .detail-meta {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 8px;
          margin-bottom: 24px;

          .meta-item {
            display: flex;
            font-size: 14px;

            .label {
              color: #95a5a6;
              width: 80px;
            }

            .value {
              color: #2c3e50;
              font-weight: 500;
            }
          }
        }

        .detail-actions {
          display: flex;
          gap: 12px;
        }
      }
    }

    .detail-content {
      padding: 24px;

      .content-section {
        margin-bottom: 32px;

        h3 {
          margin: 0 0 16px 0;
          color: #2c3e50;
          font-size: 18px;
        }

        .tech-stack-detail {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .features-list {
          list-style: none;
          padding: 0;
          margin: 0;

          li {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
            border-bottom: 1px solid #f5f5f5;

            .el-icon {
              color: #67c23a;
            }
          }
        }

        .screenshots {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 16px;

          img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
            transition: transform 0.3s ease;

            &:hover {
              transform: scale(1.05);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .admin-templates-page {
    padding: 16px;

    .page-header .header-content {
      flex-direction: column;
      text-align: center;
      gap: 20px;
    }

    .filters-section {
      flex-direction: column;
      align-items: stretch;

      .search-box {
        max-width: none;
      }
    }

    .templates-grid {
      grid-template-columns: 1fr;
    }

    .template-detail .detail-header {
      flex-direction: column;

      .detail-cover {
        width: 100%;
        height: 200px;
      }
    }
  }
}
</style>
